package com.res.simulator.handler;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.model.GenericAPIExecutionModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.transformer.APISearchTransformer;
import com.res.simulator.view.GenericAPIExecutorView;
import com.res.simulator.view.ConsumerTemplateSearchResultsView;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.dbadapter.dao.domain.ApiDefinition;

public class GenericAPIExecutionHandler implements CommonHandler<List<ConsumerTemplateSearchResultsView>, GenericAPIExecutionModel>{

	private static final Logger logger = Logger.getLogger(GenericAPIExecutionHandler.class);
	
    public List<ConsumerTemplateSearchResultsView> process(GenericAPIExecutionModel model) throws Exception {

        final APISearchTransformer tranformer = new APISearchTransformer();
        final Map<String, Object> apiDomain = tranformer.transformModelToDomian(model);

        final Map<String, Object> apiDomains = commit(apiDomain);

        List<ConsumerTemplateSearchResultsView> views = null;

        views = tranformer.transformDomianToView(apiDomains);

        return views;
    }
	
	private Map<String, Object> commit(final Map<String, Object> domainCollection) throws Exception {
		
		final CommunicationMessage message = new CommunicationMessage();

		final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
		final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

		String executorName = "APIFilter";
		logger.info("executor Name==>" + executorName);
		
		logger.info("Message Header==>" + "ReturnType:Domain|JOBType:cm" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:" + executorName);

		message.setMessageHeader("JOBType:cm|Executor:" + executorName + "|ID:" + serverAddress + "|Port:" + port);
		//message.setMessageBody(inputParamString);
		message.setObject(domainCollection);
				
		final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
        final CommunicationMessage returnedMessage = plugin.invoke(message);	 
        
        logger.info("Recieced message==> :" + returnedMessage.getMessageHeader());
        logger.info("Recieced message==> :" + returnedMessage.getMessageBody());
//        logger.info("Recieced message==> :" + returnedMessage.getObject().toString());
        
        Map<String, Object> returnCollection = null;
        final Object returnObj = returnedMessage.getObject();

        if(null != returnObj) {
            returnCollection = (Map<String, Object>) returnObj;
        }

        return returnCollection;
	}

}
